<template>
  <div class="ll-uploader">
    <Uploader
      v-model="currenValue"
      result-type="file"
      :preview-size="70"
      :max-count="maxCount"
      @before-read="beforeRead"
      @click-upload="_triggerClick"
    >
      <div class="w-70px h-70px relative">
        <img :src="uplaoderIcon" alt="" />
        <div
          class="absolute left-0 bottom-16px right-0 text-10px font-500 text-center"
          style="color: #b8caf2"
        >
          点击上传
        </div>
      </div>
    </Uploader>
    <ActionSheet
      v-model="show"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      get-container="body"
      @select="_actionSelect"
    />
  </div>
</template>

<script>
import { Uploader, ActionSheet } from "vant";
import { fetchOssUploadUrl, fetchFileUpload, fetchOssupload } from "@/services";
import uplaoderIcon from "@/assets/icon/uploader.png";
export default {
  components: {
    Uploader,
    ActionSheet,
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    capture: {
      type: Array,
      default: () => ["camera", "picture"],
    },
    maxCount: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      uplaoderIcon,
      show: false,
      fileSizeString: "",
    };
  },
  computed: {
    currenValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    actions() {
      return this.capture.map((k) => {
        return {
          name: k === "camera" ? "拍照" : "相册",
          key: k,
        };
      });
    },
  },
  methods: {
    _triggerClick(e) {
      console.log("_triggerClick");
      console.log(e);
      e.preventDefault();
      if (this.actions.length === 2) {
        this.show = true;
      } else {
        this._actionSelect(this.actions[0]);
      }
    },
    _actionSelect(action) {
      if (action.key === "camera") {
        this._captureImage();
      } else {
        this._galleryImage();
      }
    },
    /**
     * 拍照
     */
    _captureImage() {
      this._plusReady(() => {
        const cmr = plus.camera.getCamera();
        const res = cmr.supportedImageResolutions[0];
        cmr.captureImage(
          (path) => {
            console.log(path);
            this._readFile(path).then((res) => {
              this.currenValue.unshift({
                status: "uploading",
                message: "上传中...",
                file: res,
              });
              this.$nextTick(() => {
                this._uploadFile(this.currenValue[0]);
              });
            });
          },
          (e) => {
            console.log("e: ");
            console.log(e);
          },
          {
            filename: "_doc/camera/",
            resolution: res,
            format: "jpg",
          }
        );
      });
    },
    beforeRead(val) {
      console.log("beforeRead");
      console.log(val);
    },
    /**
     * 相册
     */
    _galleryImage() {
      this._plusReady(() => {
        console.log(plus.gallery);
        plus.gallery.pick(
          (paths) => {
            for (const key of paths.files) {
              this._readFile(key).then((file) => {
                this.currenValue.unshift({
                  status: "uploading",
                  message: "上传中...",
                  file: file,
                });
                this.$nextTick(() => {
                  this._uploadFile(this.currenValue[0]);
                });
              });
            }
          },
          (e) => {
            console.log("e: ", e);
          },
          {
            filter: "image",
            multiple: true,
            maximum: this.maxCount - this.currenValue.length,
          }
        );
      });
    },
    _readFile(p) {
      return new Promise((resolve, reject) => {
        this._compress(p)
          .then((p) => {
            plus.io.resolveLocalFileSystemURL(p, (entry) => {
              entry.file((file) => {
                resolve(this._turnToFile(entry, file));
              });
            });
          })
          .catch(() => {
            reject(new Error("压缩失败"));
          });
      });
    },
    _compress(p) {
      // var pathCompress = `_doc/compress/compress_${new Date().valueOf()}.jpg`; //之前文件路径
      var pathCompress = `_doc/${new Date().valueOf()}${Math.random()}.jpg`; //压缩后的文件路径
      return new Promise((resolve, reject) => {
        plus.zip.compressImage(
          {
            src: p,
            dst: pathCompress,
            overwrite: true,
            quality: 70,
            format: "jpg",
          },
          (file) => {
            resolve(file.target);
          },
          (error) => {
            reject(error);
          }
        );
      });
    },
    _turnToFile(entry, fileObj) {
      return new Promise((resolve) => {
        const reader = new plus.io.FileReader();
        reader.readAsDataURL(fileObj);
        reader.onloadend = function (e) {
          // object专成file
          let file = (function (path, name) {
            let arr = path.split(",");
            let mime = arr[0].match(/:(.*?);/)[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], name, {
              type: mime,
            });
          })(e.target.result, entry.name);
          resolve(file);
        };
      });
    },
    async _uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      // {
      //     dir: "product",
      //     fileName: file.file.name,
      //     type: file.file.type,
      //   }
      try {
        // const { fileName, host, originalName, url } = await fetchOssUploadUrl(
        //   formData
        // );

        const { fileName, host, originalName, url } = await fetchOssupload(
          formData
        );
        file.fileName = fileName;
        file.originalName = originalName;
        file.suffix = "";
        // await fetchFileUpload(url, file.file);
        file.status = "done";
        file.message = "上传成功";
        file.url = `${host}/${fileName}`;
        console.log(file.url);
        this.$emit("change", this.currenValue);
      } catch (error) {
        console.log(error);
        file.status = "failed";
        file.message = "上传失败";
      }
    },
    _plusReady(callback) {
      if (window.plus) {
        callback();
      } else {
        document.addEventListener("plusready", callback, false);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.ll-uploader {
  ::v-deep {
    .van-uploader__wrapper {
      .van-uploader__preview {
        .van-uploader__preview-image {
          @apply rounded-6px;
        }
        .van-uploader__preview-delete {
          @apply rounded-1 bg-white p-1px flex items-center justify-center;
          top: -1px;
          right: -1px;
          .van-uploader__preview-delete-icon {
            @apply rounded-1 static;
            background: #999999;
          }
        }
        .van-uploader__mask {
          @apply rounded-6px overflow-hidden;
        }
      }
    }
  }
}
</style>
